package com.study.javaBasic.linklist;

/**
 * @ClassName: LinkList
 * @Description:
 * @author: 王胜
 * @date 2021/6/18
 * @Version: 1.0
 **/
public class LinkList{
    private int data;
    private LinkList next;
    public LinkList(){
    }

    public int getData() {
        return data;
    }

    public void setData(int data) {
        this.data = data;
    }

    public LinkList getNext() {
        return next;
    }

    public void setNext(LinkList next) {
        this.next = next;
    }

    public boolean hasNext(){
        return this.next!=null;
    }

    public void showAllNext(){
        LinkList cur=this.next;
        while(cur!=null){
            System.out.println(cur);
            cur=cur.next;
        }
    }

    public void create(int size,int way){
        if(way==1){
            for (int i = 0; i < size; i++) {
                insertByHead(this,i);
            }
        }else{
            for (int i = 0; i < size; i++) {
                insertByTail(this,i);
            }
        }
    }

    public void insertByTail(LinkList head, int data) {
        LinkList cur=head;
        while(cur.hasNext()){
            cur=cur.next;
        }
        LinkList linkList = new LinkList();
        linkList.setData(data);
        cur.setNext(linkList);
    }

    public void insertByHead(LinkList head, int data) {
        LinkList cur=new LinkList();
        cur.setData(data);
        cur.setNext(head.next);
        head.next=cur;
    }

    public int size(){
        LinkList cur=this;
        int size=0;
        while (cur.hasNext()){
            size++;
            cur=cur.next;
        }
        return size;
    }

    public LinkList lastIndex(int index){
        if(index<=0){
            return null;
        }
        LinkList cur=this,indexNode=this;
        while (cur.hasNext()){
            cur=cur.getNext();
            index--;
            if(index<=0){
                indexNode=indexNode.next;
            }
        }
        if (indexNode==this){
            return null;
        }
        return indexNode;
    }
    public LinkList reverse(){
        LinkList list=new LinkList();
        if(this.hasNext())
            list=reverse(this.next);
        this.next=list.next;
        list.next=null;
        return this;
    }
    private LinkList reverse(LinkList cur){
        if(cur.hasNext()){
            LinkList link=reverse(cur.next);
            if(link.next!=null){
                cur.next=link.next;
            }
            link.next=cur;
        }
        return cur;
    }

    @Override
    public String toString() {
        return "LinkList{" +
                "data=" + data +
                '}';
    }
}
